import xlrd
from ResolveWar3 import packW3x , UnpackW3xfile_has_level , UnpackW3xfile
import os

# 提取数据
def Unpackxl(sheet,_type):
    r_obj = {
        'type' : _type
    }
    obj = []
    stirps = sheet.col_values(2)
    for _index in range(len(stirps)) :
        _parent = stirps[_index]
        if _index > 1 and len(_parent) == 4 and _parent.isalnum():
            data = {
                '_id' : sheet.cell_value(_index,1),
                '_parent' : _parent,
                'flags' : [],
            }
            for key in range(3,sheet.ncols):
                _key = sheet.cell_value(1,key).lower()
                _value = sheet.cell_value(_index,key)
                if not _value == '':
                    data['flags'].append((_key,_value))
            obj.append(data)
    r_obj['obj'] = obj
    return r_obj

def main():
    filepath = "C:\\Users\\Administrator\\Desktop\\lua_test.xls"
    ExportPath = os.path.dirname(filepath)
    xl = xlrd.open_workbook_xls(filepath)

    #提取数据
    items = Unpackxl(xl.sheet_by_name('物品'),'item')
    abilitys = Unpackxl(xl.sheet_by_name('技能'),'ability')
    units = Unpackxl(xl.sheet_by_name('单位'),'unit')
    upgrades = Unpackxl(xl.sheet_by_name('科技'),'upgrade')

    #写为字节流
    item_Byte = packW3x(items,False,None)
    ability_Byte = packW3x(abilitys,True,None)
    unit_Byte = packW3x(units,False,None)
    upgrade_Byte = packW3x(upgrades,True,None)

    #输出
    with open('newWar3map.w3t','wb') as fi:
        fi.write(item_Byte)

    with open('newWar3map.w3a','wb') as fi:
        fi.write(ability_Byte)

    with open('newWar3map.w3u','wb') as fi:
        fi.write(unit_Byte)

    with open('newWar3map.w3q','wb') as fi:
        fi.write(upgrade_Byte)

if __name__ == "__main__":
    main()
